﻿using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TestZip
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowseSource_Click(object sender, EventArgs e)
        {
            var dlg = new FolderBrowserDialog
            {
                RootFolder = Environment.SpecialFolder.MyComputer
            };
            if (dlg.ShowDialog(this) != DialogResult.OK)
                return;

            textBox1.Text = dlg.SelectedPath;
        }

        private void btnBrowseDest_Click(object sender, EventArgs e)
        {
            var dlg = new SaveFileDialog
            {
                RestoreDirectory = true,
                Filter = "Zip 文件 (*.zip)|*.zip|所有文件 (*.*)|*。*",
                DefaultExt = "zip"
            };
            if (dlg.ShowDialog(this) != DialogResult.OK)
                return;

            textBox2.Text = dlg.FileName;
        }

        private void btnCompress_Click(object sender, EventArgs e)
        {
            var files = Directory.GetFiles(textBox1.Text, "*.*", SearchOption.AllDirectories);

            var process = new CompressProcess();

            ThreadPool.QueueUserWorkItem(state =>
            {
                if (File.Exists(textBox2.Text))
                    File.Delete(textBox2.Text);

                using (ZipFile zip = new ZipFile(textBox2.Text, Encoding.UTF8))
                {
                    if (!string.IsNullOrEmpty(tbPwd.Text))
                        zip.Password = tbPwd.Text;
                    zip.SaveProgress += process.Zip_SaveProgress;

                    var entry = zip.AddDirectory(textBox1.Text);
                    //entry.FileName = "RenamedFile.txt";
                    zip.Save();
                }
            });

            process.ShowDialog(this);
        }
    }
}
